package com.vcredit.creditcat.web.api.product;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.api.product.h5.IAfterCreditManager;
import com.vcredit.creditcat.api.product.outer.IProductApplyCallbackManager;
import com.vcredit.creditcat.dto.product.outer.CustProductApplyDto;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.utils.CommonSecuritUtil;
import com.vcredit.creditcat.vo.CommonProductCreditCallbackParam;
import com.vcredit.creditcat.vo.CommonResultVo;
import com.vcredit.creditcat.vo.payday.CommonRequest;
import com.vcredit.creditcat.vo.product.ProductCreditCallbackBizData;
import com.vcredit.creditcat.vo.product.ProductLoanCallbackBizData;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.BeanUtil;
import com.vcredit.framework.util.JacksonUtil;

@Controller
public class ProductApplyCreditCallbackController {
	
	private static final Logger LOG = LoggerFactory.getLogger(ProductApplyCreditCallbackController.class);
	
	@Reference(version = "1.0")
	private IProductApplyCallbackManager productApplyCallbackManager;
	
	@Reference(version = "1.0")
	private IAfterCreditManager afterCreditManager;
	
	// 合作方的公钥（验签用）
	@Value("${request.parent.publicKey}")
	private String publicKey;
	//信用猫的私钥（解密用）
	@Value("${request.xinyongmao.privateKey}")
	private String privateKey;

	@Log
	@RequestMapping("callback/precheckstatus")
	@ResponseBody
	public CommonResultVo<Object> creditCallback(HttpServletRequest request, @RequestBody CommonProductCreditCallbackParam param) throws JsonProcessingException {
		Long productId = null;
		Long custId = null;
		CommonResultVo<Object> result = new CommonResultVo<Object>();
		try {
			CommonRequest commonRequest = new CommonRequest();
			BeanUtil.copy(param, commonRequest);
			String decryptedData = CommonSecuritUtil.getDecryptedData(commonRequest, publicKey, privateKey);
			LOG.info("------------产品申请授信结果回调参数记录  params{app_id="+param.getApp_id()+","
					+ "biz_data="+ decryptedData +"}");
			
			ProductCreditCallbackBizData bizData = JacksonUtil.Json2Obj(decryptedData, new TypeReference<ProductCreditCallbackBizData>(){});
			String user_id = bizData.getUser_id();
			Integer app_id = param.getApp_id();
			productId = (long)(app_id - 200000);
			custId = Long.parseLong(user_id.substring(user_id.indexOf("_") + 1));
			CustProductApplyDto custProductApplyDto = new CustProductApplyDto();
			custProductApplyDto.setProductId(productId);
			custProductApplyDto.setCustId(custId);
			if(bizData.getStatus() == 1) {
				custProductApplyDto.setAuditResult(1);
				custProductApplyDto.setIsApply(false);
				custProductApplyDto.setCreditApplyTime("");
				custProductApplyDto.setMaxAmount(bizData.getMax_amount().intValue() * 100);
				custProductApplyDto.setMinAmount(bizData.getMin_amount().intValue() * 100);
				custProductApplyDto.setRangeAmount(bizData.getRange_amount() * 100);
				custProductApplyDto.setLoanTerm(bizData.getLoan_term());
				custProductApplyDto.setLoanTermType(bizData.getLoan_term_type());
				custProductApplyDto.setLoanRate(bizData.getLoan_rate());
				custProductApplyDto.setServiceRate(bizData.getCutting_rate());
				custProductApplyDto.setCreditExpiretime(bizData.getAmount_validity() + " 00:00:00");
				custProductApplyDto.setCuttingAmount(bizData.getCutting_amount().multiply(new BigDecimal(100)));
				productApplyCallbackManager.creditCallback(custProductApplyDto);
			} else {
				custProductApplyDto.setAuditResult(0);
				custProductApplyDto.setIsApply(true);
				custProductApplyDto.setRejectMsg(bizData.getMsg());
				custProductApplyDto.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(DateUtils.addDays(new Date(), 30)));
			}
			result.setCode(1);
			return result;
		} catch (Exception e) {
			LOG.error("------------产品申请授信结果回调异常  !! productId="+productId+", custId="+custId, e);
			result.setCode(0);
			result.setMsg(e.getMessage());
			return result;
		}
	}
	
	/**
	 * 放款订单状态回调
	 * @author zhaoqi01
	 * @param request
	 * @param param
	 * @return
	 * @throws JsonProcessingException
	 */
	@Log
	@RequestMapping("callback/orderstatus")
	@ResponseBody
	public CommonResultVo<Object> orderstatusCallback(HttpServletRequest request, @RequestBody CommonProductCreditCallbackParam param) throws JsonProcessingException {
		Long productId = null;
		Long custId = null;
		CommonResultVo<Object> result = new CommonResultVo<Object>();
		try {
			CommonRequest commonRequest = new CommonRequest();
			BeanUtil.copy(param, commonRequest);
			String decryptedData = CommonSecuritUtil.getDecryptedData(commonRequest, publicKey, privateKey);
			LOG.info("------------产品放款提现状态回调参数记录  params{app_id="+param.getApp_id()+","
					+ "biz_data="+ decryptedData +"}");
			ProductLoanCallbackBizData bizData = JacksonUtil.Json2Obj(decryptedData, new TypeReference<ProductLoanCallbackBizData>(){});
			productId = (long)(param.getApp_id() - 200000);
			afterCreditManager.updateLoanOrderStatus(productId,bizData.getOrder_id(),bizData.getOrder_status());
			result.setCode(200);
			return result;
		} catch (Exception e) {
			LOG.error("------------产品放款提现状态结果回调异常  !! productId="+productId+", custId="+custId, e);
			result.setCode(0);
			result.setMsg(e.getMessage());
			return result;
		}
	}
	
}
